const apiService = require('../../utils/yxqzutil');
const app = getApp();
const urlWechatUserEdit = app.globalData.urlWechatUserEdit;
// pages/my-profile/basic-info.js
Component({
  properties: {

  },
  data: {
    title: '编辑信息',
    userInfo: {},
    iconLists: {},
    genderOptions: ['未知', '男', '女'],
    genderMap: { // 映射关系
      0: '未知',
      1: '男',
      2: '女'
    },
    heightRange: Array.from({
      length: 131
    }, (_, i) => `${100 + i}`),
    weightRange: Array.from({
      length: 181
    }, (_, i) => `${20 + i}`),
    selectedHeightIndex: 55,
    selectedWeightIndex: 0,
  },
  attached() {
    this.loadUserInfo();
    console.log('已经调用loadUserInfo:');
  },

  methods: {
    loadUserInfo() {
      console.log('基本信息详情页面-组件已挂载到页面');
      const userInfo = wx.getStorageSync('userInfo') || {};
      const iconLists = {
        backgroundUrl: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/basic-info.png",
        avatar: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/avatar.jpg",
        logo: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/mianyanglogo.png",
        renzheng: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/yirenzheng.png",
        paobuhao: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/icon/editInfoIcon/paobuhao.png",
        nicknameIcon: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/icon/editInfoIcon/nickname.png",
        sexIcon: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/icon/editInfoIcon/sex.png",
        weightIcon: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/icon/editInfoIcon/weight.png",
        heightIcon: "cloud://tfjkp-0ge80vu9ea710148.7466-tfjkp-0ge80vu9ea710148-1305195523/myjkp/myProfilePage/icon/editInfoIcon/height.png",
      }
      this.setData({
        userInfo: userInfo,
        iconLists: iconLists
      });
    },
    // 编辑昵称
    editNickname() {
      const userInfo = this.data.userInfo; // 从 data 中获取 userInfo
      wx.showModal({
        title: '编辑昵称',
        editable: true,
        content: userInfo.nickname || '请输入昵称',
        placeholderText: '请输入昵称',
        success: (res) => {
          if (res.confirm) {
            const newNickname = res.content.trim();
            if (newNickname.length < 2) {
              wx.showToast({
                title: '昵称不能少于2个字',
                icon: 'none',
                duration: 2000
              });
            } else if (newNickname.length > 16) {
              wx.showToast({
                title: '昵称不能超过16个字',
                icon: 'none',
                duration: 2000
              });
            } else {
              this.setData({
                'userInfo.nickname': newNickname
              });
              wx.setStorageSync('nickname', newNickname);
              this.updateUserInfo({
                nickname: newNickname
              });
            }
          }
        }
      });
    },

    // 显示性别选择器
    showGenderPicker() {
      wx.showActionSheet({
        itemList: this.data.genderOptions, // 展示文本选项
        success: (res) => {
          const selectedGenderIndex = res.tapIndex; // 选中项的索引（0, 1, 2）
          const selectedGenderValue = selectedGenderIndex; // 索引即为数据库的标准值
          const selectedGenderText = this.data.genderOptions[selectedGenderIndex]; // 获取对应文本

          // 更新前端展示
          this.setData({
            'userInfo.gender': selectedGenderValue
          });

          // 更新本地存储
          wx.setStorageSync('gender', selectedGenderValue);

          // 调用后端接口更新
          this.updateUserInfo({
            gender: selectedGenderValue
          });

          console.log(`[edit-basicinfo] 性别选择更新为: ${selectedGenderText} (${selectedGenderValue})`);
        },
        fail: (err) => {
          console.error("[edit-basicinfo] 性别选择取消或失败:", err);
        }
      });
    },


    // 选择身高
    PickerHeightChange(e) {
      const index = e.detail.value;
      const selectedHeight = this.data.heightRange[index];
      this.setData({
        selectedHeightIndex: index,
        'userInfo.height': selectedHeight
      });
      wx.setStorageSync('height', selectedHeight);
      this.updateUserInfo({
        height: selectedHeight
      });
    },

    // 选择体重
    PickerWeightChange(e) {
      const index = e.detail.value;
      const selectedWeight = this.data.weightRange[index];
      this.setData({
        selectedWeightIndex: index,
        'userInfo.weight': selectedWeight
      });
      wx.setStorageSync('weight', selectedWeight); // 确保 selectedWeight 是数字类型
      const numericWeight = parseInt(selectedWeight, 10); // 转换为数字
      this.updateUserInfo({
        weight: numericWeight
      });

    },
    // 调用后端接口更新用户信息
    // 修改后的 updateUserInfo 方法
    updateUserInfo(updatedData) {
      console.log("[edit-basicinfo] 当前修改数据:", updatedData);

      const userInfo = wx.getStorageSync("userInfo") || {}; // 获取当前本地存储的 userInfo
      const userId = parseInt(userInfo.id, 10); // 确保 userId 是数字类型

      if (!userId) {
        wx.showToast({
          title: '用户ID丢失，请重新登录',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 合并更新的字段到 userInfo
      const updatedUserInfo = {
        ...userInfo,
        ...updatedData
      };

      // 发送到后端的数据
      const dataToSend = {
        id: userId,
        ...updatedData,
      };

      console.log("[edit-basicinfo] 即将发送到后端的数据:", dataToSend);

      // 调用接口更新后端数据
      apiService.wxRequestPromise({
          url: urlWechatUserEdit.replace('{id}', userId),
          method: 'POST',
          data: dataToSend,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'charset': 'UTF-8'
          },
        })
        .then(data => {
          console.log("[edit-basicinfo] 请求成功，后端响应数据:", data);

          // 检查业务状态码
          if (data.code === 0) {
            // 更新本地存储的 userInfo
            wx.setStorageSync("userInfo", updatedUserInfo);
            console.log("[edit-basicinfo] 本地 userInfo 更新为:", updatedUserInfo);

            wx.showToast({
              title: '信息更新成功',
              icon: 'success',
              duration: 2000
            });
          } else {
            throw new Error(data.msg || '操作失败');
          }
        })
        .catch(err => {
          console.error("[edit-basicinfo] 请求失败，错误信息:", err);

          // 显示错误提示
          wx.showToast({
            title: err.message || '网络错误，请稍后再试',
            icon: 'none',
            duration: 2000
          });
        });
    },

    // 返回上一页
    goBack() {
      wx.navigateBack({
        delta: 1
      });
    }
  }
});